package com.elite;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.bill99.mgw.entity.TransInfo;
import com.bill99.mgw.util.ParseUtil;

public class EliteService extends HttpServlet{
	/**
	 * 
	 */
	private static final Log log=LogFactory.getLog(EliteService.class);
	private static final long serialVersionUID = 1L;

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * 调用doPost()方法
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		log.info("-----------------进入EliteService1服务-----------------------");
		doPost(request,response);
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * 该方法用来接收TR3和输出TR4
	 */
//	@SuppressWarnings({"unused","unchecked"})
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		log.info("-----------------进入EliteService服务-----------------------");
		
		System.out.println("-----------------进入EliteService服务-----------------------");
		
        ServletContext application;   
        WebApplicationContext wac;   
        application=getServletContext();   
        wac = WebApplicationContextUtils.getWebApplicationContext(application);//获取spring的context  
        com.elite.Elitebeaen ebean = (com.elite.Elitebeaen) wac.getBean("ebean");  
		
		
		
		
		//设置请求信息的字符编码
		request.setCharacterEncoding("utf-8");
		InputStream is = request.getInputStream();
		if (is != null) {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] receiveBuffer = new byte[2048];
			int readBytesSize = is.read(receiveBuffer);
			while (readBytesSize != -1) {
				bos.write(receiveBuffer, 0, readBytesSize);
				readBytesSize = is.read(receiveBuffer);
			}
			String reqData = new String(bos.toByteArray(), "UTF-8");
			log.info("返回TR3:"+reqData);
			//返回TR3后的第一个标志字段
			TransInfo.setRecordeText_1("TxnMsgContent");
			//返回TR3后的错误标志字段
			TransInfo.setRecordeText_2("ErrorMsgContent");
			//设置最后的解析方式
			TransInfo.setFLAG(true);

			/***************开始接收TR3**************/
			//将获取的数据传入DOM解析函数中
			HashMap respXml = ParseUtil.parseXML(reqData);
			if (respXml != null) {
				//接口版本号（version）
				String version = (String) respXml.get("version");

				//交易类型编码（txnType）
				String txnType = (String) respXml.get("txnType");

				//消息状态（interactiveStatus）
				String interactiveStatus = (String) respXml.get("interactiveStatus");

				//交易金额（amount）
				String amount = (String) respXml.get("amount");

				//商户编号		  
				String merchantId = (String) respXml.get("merchantId");

				//商户编号		  
				String settleMerchantId = (String) respXml.get("settleMerchantId");

				//终端编号（terminalId）
				String terminalId = (String) respXml.get("terminalId");

				//外部检索参考号（externalRefNumber）
				String externalRefNumber = (String) respXml.get("externalRefNumber");

				//客户号（customerId）
				String customerId = (String) respXml.get("customerId");

				//检索参考号（refNumber）
				String refNumber = (String) respXml.get("refNumber");

				//应答码（responseCode）
				String responseCode = (String) respXml.get("responseCode");

				//应答文本信息（responseTextMessage）
				String responseTextMessage=(String)respXml.get("responseTextMessage");

				//交易传输时间（transTime）
				String transTime = (String) respXml.get("transTime");

				//客户端交易时间（entryTime）
				String entryTime = (String) respXml.get("entryTime");

				//发卡组织编号（cardOrg）
				String cardOrg = (String) respXml.get("cardOrg");

				//发卡银行名称（issuer）
				String issuer = (String) respXml.get("issuer");

				//缩略卡号（storableCardNo）
				String storableCardNo = (String) respXml.get("storableCardNo");

				//授权码（authorizationCode）	
				String authorizationCode = (String) respXml.get("authorizationCode");

				//报文数字签名（signature）
				String signature = (String) respXml.get("signature");

				/********TR3接收完毕*********************************/
				//当应答码responseCode的值为00时，交易成功
				if ("00".equals(responseCode)) {
					/***************************************************************
					 * 进行数据库的逻辑操作，比如更新数据库或插入记录。
					 **************************************************************/
				String sql="insert into ivrpayhistory (version,txnType,interactiveStatus,amount," +
						"merchantid,settlemerchantid,terminalid,externalrefnumber,customerid,refnumber," +
						"responsecode,responsetextmessage,transtime,entrytime,cardorg,issuer,storablecardno," +
						"authorizationcode,signature,createddate) " +
						"values" +
						"('"+version+"','"+txnType+"','"+interactiveStatus+"',"+amount+",'"+merchantId+"','"+settleMerchantId+"'," +
						"'"+terminalId+"','"+externalRefNumber+"','"+customerId+"'," +
						"'"+refNumber+"','"+responseCode+"','"+responseTextMessage+"'," +
					    "'"+transTime+"','"+entryTime+"','"+cardOrg+"'," +
						"'"+issuer+"','"+storableCardNo+"','"+authorizationCode+"','"+signature+"',sysdate)";
				log.info("SQL:"+sql);
				try{
					int a=ebean.update(sql);
					log.info("插入结果:"+a);
				}catch(Exception e){
					
				}

				
				
				}
				/********输出TR4************************************/
				StringBuffer tr4XML = new StringBuffer();
				tr4XML.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><MasMessage xmlns=\"http://www.99bill.com/mas_cnp_merchant_interface\"><version>1.0</version><TxnMsgContent>");
				tr4XML.append("<txnType>").append(txnType).append("</txnType>");
				tr4XML.append("<interactiveStatus>TR4</interactiveStatus>");
				tr4XML.append("<merchantId>").append(merchantId).append("</merchantId>");
				if (settleMerchantId != null && "".equals(settleMerchantId)) {
					tr4XML.append("<settleMerchantId>").append(settleMerchantId).append("</settleMerchantId>");
				}
				tr4XML.append("<terminalId>").append(terminalId).append("</terminalId>");
				tr4XML.append("<refNumber>").append(refNumber).append("</refNumber>");
				tr4XML.append("</TxnMsgContent></MasMessage>");
				log.info("TR4:"+tr4XML.toString());
				response.getOutputStream().write(new String(tr4XML).getBytes("UTF-8"));
			}
		}else{
			log.info("---------------------------未收到报文--------------------------------");
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
//	@Override
//	public void init(ServletConfig config) throws ServletException {
////		super.init();
//	}
}
